<template>
  <div class="login-wrap" style="background-image: url('../static/loginbg.jpg')">
    <el-form v-show="login" label-position="left" :model="ruleForm" :rules="rules" ref="ruleForm" label-width="0px"
             class="demo-ruleForm login-container">
      <h3 class="title">用户登录</h3>
      <el-form-item prop="username">
        <el-input type="text" v-model="ruleForm.accountNumber" auto-complete="off" placeholder="账号"></el-input>
      </el-form-item>
      <el-form-item prop="password">
        <el-input type="password" v-model="ruleForm.password" auto-complete="off" placeholder="密码"></el-input>
      </el-form-item>
      <!--      <el-checkbox class="remember" v-model="rememberpwd">记住密码</el-checkbox>-->
      <!--      <el-button type="text" @click="toRePassword">找回密码</el-button>-->
      <el-form-item style="width:100%;">
        <el-button type="primary" style="width:45%;" @click="userLogin()" :loading="logining">登录
        </el-button>
        <el-button style="width:45%;" @click="toRegister()" :loading="logining">注册</el-button>
      </el-form-item>
    </el-form>
    <!--  注册  -->
    <el-form v-show="register" label-position="left" :model="ruleForm" :rules="rules" ref="ruleForm" label-width="0px"
             class="demo-ruleForm login-container">
      <h3 class="title">用户注册</h3>
      <el-form-item prop="imgPath">
        <el-upload
          class="avatar-uploader"
          action="http://localhost:8077/share/hope/common/upload-avatar"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload">
          <img v-if="imgPath" :src="'http://localhost:8077/share/hope/common/view-avatar?path='+imgPath"
               class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>
      <el-form-item prop="username">
        <el-input type="text" v-model="ruleForm.name" auto-complete="off" placeholder="名字"></el-input>
      </el-form-item>
      <el-form-item prop="account">
        <el-input type="text" v-model="ruleForm.accountNumber" auto-complete="off" placeholder="账号"></el-input>
      </el-form-item>
      <el-form-item prop="password">
        <el-input type="password" v-model="ruleForm.password" auto-complete="off" placeholder="密码"></el-input>
      </el-form-item>
      <el-form-item prop="rePassword">
        <el-input type="password" v-model="ruleForm.newPassword" auto-complete="off" placeholder="确认密码"></el-input>
      </el-form-item>

      <el-form-item style="width:100%;">
        <el-button type="primary" style="width:45%;" @click="userRegister()" :loading="logining">注册</el-button>
        <el-button type="info" style="width:45%;" @click="returnLogin()" :loading="logining">返回登录</el-button>
      </el-form-item>
    </el-form>
    <!--    找回密码-->
    <el-dialog
      title="找回密码"
      :visible.sync="forgetPassword"
      width="80%">

      <span slot="footer" class="dialog-footer">
    <el-button @click="forgetPassword = false">取 消</el-button>
    <el-button type="primary" @click="rePassword()">确 定</el-button>
  </span>
      <h2>重置密码</h2>
      <el-form ref="form" :model="ruleForm" :rules="rerules" label-width="100px">
        <el-form-item prop="username">
          <el-input type="text" v-model="ruleForm.name" auto-complete="off" placeholder="名字"></el-input>
        </el-form-item>
        <el-form-item prop="username">
          <el-input type="text" v-model="ruleForm.accountNumber" auto-complete="off" placeholder="账号"></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input type="password" v-model="ruleForm.password" auto-complete="off" placeholder="新密码"></el-input>
        </el-form-item>
        <el-form-item prop="confirmPassword">
          <el-input type="password" v-model="ruleForm.newPassword" auto-complete="off"
                    placeholder="确认密码"></el-input>
        </el-form-item>
        <el-form-item style="width:100%;">
          <el-button type="primary" style="width:45%;" @click="rePassword()" :loading="logining">点击重置</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>
<script type="text/ecmascript-6">
import {login} from '../api/userMG'
import {setCookie, getCookie, delCookie} from '../utils/util'
import md5 from 'js-md5'

export default {
  name: 'login',
  data() {
    return {
      forgetPassword: false,
      register: false,
      login: true,
      //定义loading默认为false
      logining: false,
      // 记住密码
      rememberpwd: false,
      ruleForm: {
        //username和password默认为空
        name: '',
        accountNumber: '',
        password: '',
        newPassword: '',
        code: '',
        randomStr: '',
        codeimg: ''
      },
      user: {},
      imgPath: '',
      //rules前端验证
      rules: {
        name: [{required: true, message: '请输入名字', trigger: 'blur'}],
        accountNumber: [{required: true, message: '请输入账号', trigger: 'blur'}],
        password: [{required: true, message: '请输入密码', trigger: 'blur'}],
        code: [{required: true, message: '请输入验证码', trigger: 'blur'}]
      },
      rerules: {
        password: [
          {required: true, message: '请输入新密码', trigger: 'blur'},
          {
            validator: (rule, value, callback) => {
              if (
                /^(?=.*[A-Z])(?=.*[a-z])(?=.*\d)[A-Za-z\d]{8,16}$/.test(
                  value
                )
              ) {
                callback();
              } else {
                callback(new Error('密码必须包含至少1个大写字母、1个小写字母和1个数字，长度在8-16之间'));
              }
            },
            trigger: 'blur',
          },
        ],
        newPassword: [
          {required: true, message: '请再次输入密码', trigger: 'blur'},
          {
            validator: (rule, value, callback) => {
              if (value === this.form.password) {
                callback();
              } else {
                callback(new Error('两次输入的密码不一致'));
              }
            },
            trigger: 'blur',
          },
        ],
      },
    }
  },
  // 创建完毕状态(里面是操作)
  created() {
    // this.$message({
    //   message: '账号密码及验证码不为空即可',
    //   type: 'success'
    // })
    // 获取图形验证码
    // this.getcode()
    // 获取存在本地的用户名密码
    this.getuserpwd()

  },
  // 里面的函数只有调用才会执行
  methods: {
    handleAvatarSuccess(res, file) {
      this.imgPath = res.msg
    },
    beforeAvatarUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 5;
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 5MB!');
      }
      return isLt2M;
    },
    toRePassword() {
      this.forgetPassword = true
    },
    async rePassword() {

    },
    toRegister() {
      this.register = true
      this.login = false
    },
    returnLogin() {
      this.register = false
      this.login = true
    },
    async userRegister() {
      const request = {
        name: this.ruleForm.name,
        accountNumber: this.ruleForm.accountNumber,
        password: this.ruleForm.password,
        newPassword: this.ruleForm.newPassword,
        imgPath: this.imgPath
      }
      this.$axios.post('user/register', request).then(res => {
        if (res.status === 200) { //成功
          this.register = false
          this.login = true
          this.$message.success(res.data)
        } else { //失败
          this.$message.error(res.data)
        }
      })
    },
    async userLogin() {
      const request = {
        accountNumber: this.ruleForm.accountNumber,
        password: this.ruleForm.password
      }
      this.$axios.post('user/login', request).then(res => {
        if (res.data.code === 20000) { //成功
          this.$message.success(res.data.msg)
          console.log(res.data.data)
          localStorage.setItem("userInfo", JSON.stringify(res.data.data));
          if (res.data.data.roleNum === 0) {
            this.$router.push("/system/calendar")
          }
          if (res.data.data.roleNum === 1) {
            this.$router.push("/system/LoveProduct")
          }
        } else { //失败
          this.$message.error(res.data.msg)
        }
      });
    },
    // 获取用户名密码
    getuserpwd() {
      if (getCookie('user') != '' && getCookie('pwd') != '') {
        this.ruleForm.username = getCookie('user')
        this.ruleForm.password = getCookie('pwd')
        this.rememberpwd = true
      }
    },
    //获取info列表
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.logining = true
          // 测试通道，不为空直接登录
          setTimeout(() => {
            this.logining = false
            this.$store.commit('login', 'true')
            this.$router.push({path: '/goods/Goods'})
          }, 1000)
          // 注释
          login(this.ruleForm).then(res => {
            if (res.success) {
              if (this.rememberpwd) {
                //保存帐号到cookie，有效期7天
                setCookie('user', this.ruleForm.username, 7)
                //保存密码到cookie，有效期7天
                setCookie('pwd', this.ruleForm.password, 7)
              } else {
                delCookie('user')
                delCookie('pwd')
              }
              //如果请求成功就让他2秒跳转路由
              setTimeout(() => {
                this.logining = false
                // 缓存token
                localStorage.setItem('logintoken', res.data.token)
                // 缓存用户个人信息
                localStorage.setItem('userdata', JSON.stringify(res.data))
                this.$store.commit('login', 'true')
                this.$router.push({path: '/goods/Goods'})
              }, 1000)
            } else {
              this.$message.error(res.msg)
              this.logining = false
              return false
            }
          })
        } else {
          // 获取图形验证码
          // this.getcode()
          this.$message.error('请输入用户名密码！')
          this.logining = false
          return false
        }
      })
    }
  }
}
</script>

<style scoped>
.login-wrap {
  box-sizing: border-box;
  width: 100%;
  height: 100%;
  padding-top: 10%;
  background-image: url();
  /* background-color: #112346; */
  background-repeat: no-repeat;
  background-position: center right;
  background-size: 100%;
}

.login-container {
  border-radius: 10px;
  margin: 0px auto;
  width: 350px;
  padding: 30px 35px 15px 35px;
  background: #fff;
  border: 1px solid #eaeaea;
  text-align: left;
  box-shadow: 0 0 20px 2px rgba(0, 0, 0, 0.1);
}

.title {
  margin: 0px auto 40px auto;
  text-align: center;
  color: #505458;
}

.remember {
  margin: 0px 0px 35px 0px;
}

.code-box {
  text-align: right;
}

.codeimg {
  height: 40px;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader {
  border: 1px solid #d9d9d9;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
